package com.studerb.view;

import java.awt.Component;
import java.util.EventObject;

import javax.swing.JOptionPane;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class GnusbinApp extends SingleFrameApplication {
    /**
     * A convenient static getter for the application instance.
     * @return the instance of GnusbinApp
     */
    public static GnusbinApp getApplication() {
        return Application.getInstance(GnusbinApp.class);
    }
    /**
     * Main method launching the application.
     */
    public static void main(String[] args) {
        launch(GnusbinApp.class, args);
    }

    private AbstractApplicationContext springAppContext;

    Logger logger = Logger.getLogger(GnusbinApp.class);

    /**
     * This method is to initialize the specified window by injecting resources.
     * Windows shown in our application come fully initialized from the GUI
     * builder, so this additional configuration is not needed.
     */
    @Override protected void configureWindow(java.awt.Window root) {
    }

    @Override protected void initialize(String[] args) {
        try{
            logger.info("Initializing Spring App Context");
            super.initialize(args);
            springAppContext = new ClassPathXmlApplicationContext("applicationContext.xml");
            assert (springAppContext != null);
            springAppContext.registerShutdownHook();
        }
        catch(Exception e){
            logger.error(ExceptionUtils.getRootCauseMessage(e));
            e.printStackTrace();
            end();
        }

    }

    @Override protected void startup() {
        this.addExitListener(new ConfirmExit());
        show(new GnusbinView(this));
    }
}

class ConfirmExit implements Application.ExitListener {
    public boolean canExit(EventObject e) {
        Object source = (e != null) ? e.getSource() : null;
        Component owner = (source instanceof Component) ? (Component)source : null;
        int option = JOptionPane.showConfirmDialog(owner, "Really Exit?");
        return option == JOptionPane.YES_OPTION;
    }

    @Override public void willExit(EventObject arg0) {
    }
}